<template>
  <a-drawer
      title="客户跟进"
      :visible="visible"
      :destroyOnClose="true"
      :width="460"
      :body-style="{
      height: 'calc(100% - 100px)',
      boxSizing: 'border-box',
      padding: '16px 0',
    }"
      @close="onClose"
  >
    <div class="drawer-content">
      <a-radio-group v-model:value="activeKey" class="radio-box" button-style="solid">
        <a-radio-button value="1" style="flex: 1">跟进客户</a-radio-button>
        <a-radio-button value="2" style="flex: 1">客户信息</a-radio-button>
      </a-radio-group>
      <div class="content-box">
        <a-form layout="vertical">
          <a-row :wrap="true" :gutter="12" v-show="activeKey == 1">
            <a-col :span="24">
              <a-form-item label="变更客户状态" v-bind="validateInfos['followInfo.status']">
                <a-select
                    v-model:value="formData.followInfo.status"
                    :options="customerStatusOptions"
                    placeholder="请选择变更客户状态"
                    :allowClear="true"
                    style="width: 100%"
                    @change="onStatusChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="statusType !== 'success'">
              <a-form-item label="跟进内容" v-bind="validateInfos['followInfo.remark']">
                <a-textarea
                    placeholder="请输入"
                    :auto-size="{ minRows: 3 }"
                    v-model:value="formData.followInfo.remark"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="跟进图片">
                <a-upload
                    :action="imgAction"
                    v-model:file-list="fileList"
                    :multiple="false"
                    accept="image/*"
                    name="image"
                    list-type="picture-card"
                    :headers="{ 'org-token': $store.getters.token }"
                    :data="{ dir: 'org_village' }"
                    @change="handleUploadChange"
                >
                  <div v-if="fileList.length < 6">
                    <PlusOutlined/>
                    <div style="padding-top: 4px">上传</div>
                  </div>
                </a-upload>
              </a-form-item>

            </a-col>
            <a-col :span="24" v-if="statusType !== 'end' && statusType !== 'success'">
              <a-form-item label="下次跟进时间"
                           v-bind="validateInfos['followInfo.followup_nexttime']">
                <a-date-picker
                    class="w-100p"
                    v-model:value="formData.followInfo.followup_nexttime"
                    valueFormat="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24" v-if="statusType === 'success'">
              <a-form-item label="绑定合同" v-bind="validateInfos['followInfo.contracts']">
                <a-select
                    v-model:value="formData.followInfo.contracts"
                    show-search
                    placeholder="输入合同编号/经办人/租客名称以搜索"
                    :default-active-first-option="false"
                    mode="multiple"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    :options="contractsList"
                    @search="handleContractInputChange"
                    @change="onContractChange"
                />
              </a-form-item>
            </a-col>

            <a-col :span="24" v-if="formData.customerInfo.channel_id">
              <a-form-item label="是否公开到渠道"
                           v-bind="validateInfos['followInfo.public_channel']">
                <a-switch
                    :checkedValue="1"
                    :unCheckedValue="0"
                    v-model:checked="formData.followInfo.public_channel"
                />
              </a-form-item>
            </a-col>

            <!--   跟进历史   -->
            <a-col :span="24">
              <div style="margin-bottom: 16px">跟进历史</div>
              <a-timeline v-if="followList.length">
                <a-timeline-item v-for="(item, index) in followList" :key="index">
                  <p v-if="item?.created_at">{{ item.created_at }}</p>
                  <p v-if="item?.operate_content?.status_txt">
                    状态：{{ item.operate_content?.status_txt }}</p>
                  <p v-if="item?.operate_content?.remark">
                    内容：{{ item.operate_content?.remark }}</p>
                  <div class="mb-10 flex" v-if="item.operate_content?.followup_img?.length>0">
                    <span>跟进图片：</span>
                    <a-space>
                      <a-image v-for="img in item.operate_content?.followup_img" :src="img.url"
                               :width="40"/>
                    </a-space>
                  </div>
                  <p v-if="item?.operate_content?.user_name">
                    跟进人：{{ item?.operate_content?.user_name }}
                    {{ item?.operate_content?.user_phone }}
                  </p>
                </a-timeline-item>
              </a-timeline>

              <a-empty v-else/>
            </a-col>

          </a-row>
          <a-row :wrap="true" :gutter="12" v-show="activeKey == 2">
            <a-col :span="24">
              <a-form-item label="客户姓名" v-bind="validateInfos['customerInfo.name']">
                <a-input
                    v-model:value="formData.customerInfo.name"
                    placeholder="请填写客户姓名"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="客户电话" v-bind="validateInfos['customerInfo.tel']">
                <a-input
                    v-model:value="formData.customerInfo.tel"
                    placeholder="请输入手机号码"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="公司" v-bind="validateInfos['customerInfo.company']">
                <a-input
                    v-model:value="formData.customerInfo.company"
                    placeholder="请输入公司"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="行业" v-bind="validateInfos['customerInfo.industry']">
                <a-select
                    v-model:value="formData.customerInfo.industry"
                    :options="industryOptions"
                    placeholder="请填选择行业"
                >
                  <template #dropdownRender="{ menuNode: menu }">
                    <v-nodes :vnodes="menu"/>
                    <a-divider style="margin: 4px 0"/>
                    <div
                        style="
                          padding: 4px 8px;
                          cursor: pointer;
                          color: #1890ff;
                          text-align: center;
                        "
                        @mousedown="(e) => e.preventDefault()"
                        @click="addTag"
                    >
                      添加
                    </div>
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="意向项目" v-bind="validateInfos['customerInfo.build_ids']">
                <a-cascader
                    v-model:value="formData.customerInfo.build_ids"
                    :options="optionsBuild"
                    placeholder="请选择"
                    @change="buildChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="预计签约时间"
                           v-bind="validateInfos['customerInfo.expect_contract']">
                <a-date-picker
                    class="w-100p"
                    v-model:value="formData.customerInfo.expect_contract"
                    valueFormat="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="需求面积段"
                           v-bind="validateInfos['customerInfo.expect_area_max']">
                <a-input-group size="default">
                  <a-row :gutter="8">
                    <a-col :span="8">
                      <a-input-number
                          v-model:value="formData.customerInfo.expect_area_min"
                          addon-after="m²"
                          placeholder="最小值"
                          :min="0"
                          :precision="2"
                      />
                    </a-col
                    >
                    -
                    <a-col :span="8">
                      <a-input-number
                          v-model:value="formData.customerInfo.expect_area_max"
                          addon-after="m²"
                          placeholder="最大值"
                          :min="0"
                          :precision="2"
                      />
                    </a-col>
                  </a-row>
                </a-input-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="客户预算" v-bind="validateInfos['customerInfo.budget_amount']">
                <a-input-number v-model:value="formData.customerInfo.budget_amount" addon-after="元"
                                style="width: 100%" :min="0" :precision="2"/>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item v-bind="validateInfos['customerInfo.channel_id']">
                <template #label>
                  <span>关联渠道</span>
                  <text-tip
                      tips="关联渠道与意向项目关联，请先选择意向项目"
                  />
                </template>
                <a-select
                    v-model:value="formData.customerInfo.channel_id"
                    :options="channelList"
                    placeholder="请选择关联渠道"
                    :allowClear="true"
                    style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="成交几率" v-bind="validateInfos['customerInfo.deal_precent']">
                <Slider
                    :tip-formatter="(value) => {return `${value}%`}"
                    v-model:value="formData.customerInfo.deal_precent"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="标签" v-bind="validateInfos['customerInfo.tag_id']">
                <template v-for="(tag, index) in selectTags" :key="index">
                  <a-tag :closable="true" @close="handleCloseTag(tag)">
                    {{ tag.name }}
                  </a-tag>
                </template>
                <a-tag color="blue" style="background: #fff; cursor: pointer" @click="handleAddTag">
                  <PlusOutlined/>
                  添加
                </a-tag>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="备注" v-bind="validateInfos['customerInfo.remark']">
                <a-textarea
                    placeholder="请输入"
                    :auto-size="{ minRows: 3 }"
                    v-model:value="formData.customerInfo.remark"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

    </div>

    <div class="drawer-footer">
      <a-row type="flex" justify="space-between" style="width: 100%">
        <a-button danger @click.stop="handleSendBackSea">退回公海</a-button>
        <a-space>
          <a-button @click.prevent="onClose"> 取消</a-button>
          <a-button type="primary" @click.prevent="onSubmit" :loading="submitLoading"> 提交
          </a-button>
        </a-space>
      </a-row>
    </div>

    <SelectTagModal
        :visible="addTagVisible"
        :tags="selectTags"
        @success="selectTagSuccess"
        @handleCancel="addTagVisible = false"
    />

    <!-- 行业分类 -->
    <EditTag
        @closeTag="editTagClose"
        @success="editSuccess"
        :visible="editVisible"
    ></EditTag>
  </a-drawer>
</template>
<script>
import {defineComponent, reactive, toRefs, computed, watch, createVNode, ref} from "vue";
import {Form, Slider, message, Modal} from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import moment from "moment";
import _ from "lodash";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import SelectTagModal from "@/views/village/BusinessManage/tagModules/SelectTagModal.vue";
import {
  TextTip,
} from "bl-common-vue3";
import EditTag from "@/views/village/BusinessManage/modules/EditTag.vue";

export default defineComponent({
  name: "FollowUpCustomer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    EditTag,
    Slider,
    PlusOutlined,
    SelectTagModal,
    TextTip,
    VNodes: (_, {attrs}) => {
      return attrs.vnodes;
    },
  },
  setup(props, {emit}) {
    const REQUIRE_RULE = [{required: true, message: "必填项"}];
    const state = reactive({
      activeKey: '1',
      customerStatusOptions: [],
      contractsList: [], // 合同列表
      selectContracts: [], // 选择的合同列表
      selectTags: [],
      statusType: '', // success 成交 end 结束
      rulesData: {
        "customerInfo.name": REQUIRE_RULE,
        "customerInfo.tel": REQUIRE_RULE,
        "customerInfo.village_id": REQUIRE_RULE,
        "followInfo.status": REQUIRE_RULE,
        "customerInfo.build_ids": REQUIRE_RULE,
      },
      addTagVisible: false,
      followList: [],
      submitLoading: false,
      channelObject: {},
      channelList: [],
      industryOptions: [],
      editVisible: false,
    });
    const formData = reactive({
      customerInfo: {
        name: '',
        tel: '',
        company: '',
        village_id: undefined,
        budget_amount: undefined, // 客户预算金额
        expect_contract: undefined, // 预计签约时间
        expect_area_min: undefined,
        expect_area_max: undefined,
        channel_id: undefined, // 关联渠道
        remark: '', // 备注
        deal_precent: undefined, //成交几率
        tag_id: [], // 标签
        industry: undefined,
        build_ids: [],
        build_id: undefined,
      },
      followInfo: {
        status: undefined,
        remark: '', // 跟进内容
        followup_nexttime: undefined,
        contracts: undefined, // 绑定的合同
        public_channel: 1,
      }

    });

    const disabledDate = (current) => {
      return current < moment().startOf("day");
    };

    const {resetFields, validate, validateInfos} = useForm(formData, state.rulesData);

    const getContractList = (keywords) => {
      return new Promise((resolve) => {
        request
            .get("/org", "/business/contract/search", {keyword: keywords})
            .then((res) => {
              state.contractsList = res.list.map((item) => ({
                value: item.id,
                label: item.contract_number,
              }));
              resolve();
            });
      });
    };

    let timeout = null;
    const handleContractInputChange = (value) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      timeout = setTimeout(() => {
        getContractList(value);
      }, 600);
    };

    const saveFollowup = () => {
      return new Promise((resolve, reject) => {
        let params = {
          id: props.id,
        };
        for (let key in formData.followInfo) {
          if (formData.followInfo[key] || formData.followInfo[key] === 0) {
            params[key] = formData.followInfo[key];
          }
        }
        if (!formData.customerInfo.channel_id) {
          delete params.public_channel
        }
        params.contracts = _.cloneDeep(state.selectContracts).map((v) => {
          return {
            id: v.value,
            contract_number: v.label,
          }
        })
        if (fileList.value.length > 0) {
          params.followup_img = fileList.value.map(item => {
            return {
              name: item.name,
              url: item.url
            }
          })
        }
        request
            .post("/org", "/business/customer/followup", params)
            .then((res) => {
              resolve();
            }).catch(() => {
          reject();
        });
      });
    };

    const saveBasic = () => {
      return new Promise((resolve, reject) => {
        let params = {
          id: props.id,
        };
        for (let key in formData.customerInfo) {
          if (formData.customerInfo[key] || formData.customerInfo[key] === 0) {
            params[key] = formData.customerInfo[key];
          }
        }
        params.tag_id = _.cloneDeep(state.selectTags).map((v) => v.id);
        if (params.build_ids?.length > 0) {
          params.village_id = params.build_ids[0];
          params.build_id =
              params.build_ids.length > 1 ? params.build_ids[1] : undefined;
        }
        delete params.build_ids;
        request
            .put("/org", "/business/customer", params)
            .then((res) => {
              resolve();
            }).catch(() => {
          reject();
        });
      });
    };

    const industryList = () => {
      request.get("/org", "/manage/taglib/industry/all").then((res) => {
        if (res.list.length) {
          state.industryOptions = res.list.map((item) => {
            return {
              value: item.id,
              label: item.name,
              id: item.id,
            };
          });
        }
      });
    };

    const onSubmit = () => {
      validate().then(async () => {
        // 跟进
        state.submitLoading = true;
        saveFollowup().then(() => {
          saveBasic().then(() => {
            state.submitLoading = false;
            emit("success");
          })
        })
      }).catch((err) => {
        message.warning('请检查填写信息');
        if (err?.errorFields[0].name.includes('customerInfo')) {
          state.activeKey = '2';
        } else {
          state.activeKey = '1';
        }
      });
    };

    const handleSendBackSea = () => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要将该客户退回公海吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
              .get("/org", "/business/customer/return", {id: props.id})
              .then((res) => {
                message.success(res?.msg || '退回成功');
                emit("success");
              })
        },
      });
    };

    const onClose = () => {
      emit("handleCancel");
    };

    const getHistory = () => {
      request.get("/org", "/business/customer/followupList", {id: props.id}).then((res) => {
        state.followList = res?.list || [];
      });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        formData.customerInfo[key] = state[key];
      }
      if (state.village_id) {
        formData.customerInfo.build_ids[0] = state.village_id;
      }
      if (state.village_id && state.build_id) {
        formData.customerInfo.build_ids[1] = state.build_id;
      }
    };

    const addTag = () => {
      state.editVisible = true;
    };
    const editTagClose = () => {
      state.editVisible = false;
    };
    const editSuccess = () => {
      editTagClose();
      industryList();
    };

    const getDetail = () => {
      request.get("/org", "/business/customer/detail", {id: props.id}).then((res) => {
        const detail = res.detail;
        setModelRef({
          name: detail.name,
          tel: detail.tel,
          company: detail.company,
          village_id: detail.village_id,
          budget_amount: detail.budget_amount, // 客户预算金额
          expect_contract: detail.expect_contract, // 预计签约时间
          expect_area_min: detail.expect_area_min || 0,
          expect_area_max: detail.expect_area_max,
          channel_id: detail.channel_id, // 关联渠道
          remark: detail.remark, // 备注
          deal_precent: detail.deal_precent || 0, //成交几率
          tag_id: detail.tag_id || [], // 标签
          industry: detail.industry,
          build_id: detail.build_id,
        });
        state.selectTags = _.cloneDeep(detail?.tag_arr || []);
        getChannelList(true);
      })
    };

    const onContractChange = (value, option) => {
      state.selectContracts = _.cloneDeep(option);
    };

    const getStatus = () => {
      request.get("/org", "/business/customer/statusList", {}).then((res) => {
        state.customerStatusOptions = res.list.map((item) => ({
          value: item.status,
          label: item.name,
          ...item,
        }));
      });
    };

    const onStatusChange = (value, option) => {
      if (option) {
        state.statusType = option?.status == 30 ? 'success' : option?.is_end == 1 ? 'end' : '';
      } else {
        state.statusType = '';
      }
      if (state.statusType == 'success') {
        state.rulesData["followInfo.contracts"] = REQUIRE_RULE;
      } else {
        delete state.rulesData["followInfo.contracts"];
      }
    };

    const handleCloseTag = (removedTag) => {
      state.selectTags = state.selectTags.filter(tag => tag.id !== removedTag.id);
    };

    const handleAddTag = () => {
      state.addTagVisible = true;
    };

    const selectTagSuccess = (data) => {
      state.selectTags = _.cloneDeep(data);
      state.addTagVisible = false;
    };

    const getChannelList = (notReset = false) => {
      const key = "channel" + formData.customerInfo.village_id;
      if (!notReset) {
        formData.customerInfo.channel_id = undefined;
      }
      if (formData.customerInfo.village_id) {
        if (Object.keys(state.channelObject).includes(key)) {
          state.channelList = state.channelObject[key];
        } else {
          request
              .get("/org", "/business/customer/channel/index", {
                village_id: formData.customerInfo.village_id,
              })
              .then((res) => {
                const list = res.list.map((item) => {
                  return {
                    value: item.id,
                    label: item.name,
                  };
                });
                state.channelList = list;
                state.channelObject[key] = list;
              });
        }
      } else {
        state.channelList = [];
      }
    };

    const buildChange = (value) => {
      if (value?.length > 0) {
        formData.customerInfo.village_id = value[0];
      }
      getChannelList();
    };

    // 意向楼宇
    const optionsBuild = ref([]);
    const getBuildList = () => {
      request
          .get("/org", "/build/villageAndBuildList/v2")
          .then((res) => {
            const vList = res.villageList.map((item) => {
              return {
                label: item.name,
                value: item.id,
                children: item.buildList.map((childItem) => {
                  return {
                    label: childItem.build_name,
                    value: childItem.id,
                  };
                }),
              };
            });
            optionsBuild.value = vList;
          });
    };

    const init = () => {
      getBuildList();
      // 获取跟进客户状态
      getStatus();
      // 获取跟进历史
      getHistory();
      // 获取行业分类
      industryList();
      // 获取客户详情
      getDetail();

    };

    const reset = () => {
      state.activeKey = '1';
      state.customerStatusOptions = [];
      state.contractsList = [];
      state.selectContracts = [];
      state.selectTags = [];
      state.statusType = '';
      state.followList = [];
      state.submitLoading = false;
      state.channelList = [];
      state.channelObject = {};
      state.industryOptions = [];
      optionsBuild.value = [];
      fileList.value = [];
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            reset();
          }
        }
    );

    const fileList = ref([]);
    // 上传
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length > 0) {
        // console.log(resFileList, "取最后一条数据之前");
        resFileList = resFileList.slice(-1);
        // console.log(resFileList, "取最后一条数据");

        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;

              // fileList.value.push({
              //   name: file.name,
              //   url: file.fileUrl,
              // });
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });

        console.log(resFileList, "最终数据");

        console.log(fileList.value);
      }
    };

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      optionsBuild,
      onClose,
      onSubmit,
      disabledDate,
      handleContractInputChange,
      onContractChange,
      onStatusChange,
      handleCloseTag,
      handleAddTag,
      reset,
      selectTagSuccess,
      handleSendBackSea,
      getChannelList,
      addTag,
      editTagClose,
      editSuccess,
      buildChange,
      fileList,
      handleUploadChange,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
    };
  },
});
</script>

<style lang="less" scoped>
.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.radio-box {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  text-align: center;
  padding: 0 16px;
}

.content-box {
  flex: 1;
  padding: 0 16px;
  overflow: auto;
}

:deep(.ant-drawer-body) {
  padding: 16px 0 !important;
}

.ant-tag {
  margin: 4px 8px 4px 0;
}

:deep(.ant-image-img) {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
}

</style>